package com.harmony.pilot.knowledge.controller;

import com.harmony.pilot.knowledge.entity.CodeSnippet;
import com.harmony.pilot.knowledge.service.CodeCompletionService;
import com.harmony.pilot.knowledge.service.CodeCompletionService.*;
import com.harmony.pilot.knowledge.service.CodeQLIntegrationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 代码补全控制器
 * 提供代码补全、续写、参数提示等API
 */
@Slf4j
@RestController
@RequestMapping("/api/knowledge/completion")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class CompletionController {
    
    private final CodeCompletionService completionService;
    private final CodeQLIntegrationService codeQLIntegrationService;
    
    @Value("${knowledge.codeql.enable:true}")
    private boolean codeQLEnabled;
    
    /**
     * 根据关键词搜索补全建议
     * 
     * POST /api/knowledge/completion/search
     * 
     * Request:
     * {
     *   "keyword": "napi_create_",
     *   "currentFile": "foundation/arkui/napi/test.cpp",
     *   "context": "...",
     *   "maxResults": 10
     * }
     */
    @PostMapping("/search")
    public CompletionResponse searchCompletions(@RequestBody CompletionRequest request) {
        log.info("代码补全搜索: keyword={}, useCodeQL={}", request.getKeyword(), 
                request.getUseCodeQL() != null ? request.getUseCodeQL() : codeQLEnabled);
        
        // 1. 先从知识库搜索
        CompletionResponse kbResponse = completionService.generateCompletions(
            request.getKeyword(),
            request.getCurrentFile(),
            request.getContext(),
            request.getMaxResults() != null ? request.getMaxResults() : 10
        );
        
        // 2. 如果启用CodeQL，使用AST增强结果
        boolean useCodeQL = request.getUseCodeQL() != null ? request.getUseCodeQL() : codeQLEnabled;
        if (useCodeQL && codeQLIntegrationService != null) {
            try {
                List<CodeQLIntegrationService.CompletionItem> enhancedItems = 
                    codeQLIntegrationService.enhanceCompletionsWithAST(
                        request.getKeyword(),
                        request.getContext(),
                        request.getCurrentFile(),
                        kbResponse.getItems().stream()
                            .map(item -> {
                                CodeSnippet snippet = new CodeSnippet();
                                snippet.setSummary(item.getLabel());
                                snippet.setFilePath(item.getDetail());
                                snippet.setContent(item.getDocumentation());
                                snippet.setSnippetType(mapKindToSnippetType(item.getKind()));
                                return snippet;
                            })
                            .collect(java.util.stream.Collectors.toList())
                    );
                
                // 转换回CompletionItem（简化处理）
                // 实际应该合并结果并去重
                log.info("CodeQL增强完成: {} 个结果", enhancedItems.size());
            } catch (Exception e) {
                log.warn("CodeQL增强失败，使用知识库结果", e);
            }
        }
        
        return kbResponse;
    }
    
    private String mapKindToSnippetType(String kind) {
        if (kind == null) return "UNKNOWN";
        switch (kind) {
            case "Function": return "FUNCTION";
            case "Class": return "CLASS";
            case "Method": return "METHOD";
            case "Field": return "FIELD";
            default: return "UNKNOWN";
        }
    }
    
    /**
     * 生成代码续写
     * 
     * POST /api/knowledge/completion/continue
     * 
     * Request:
     * {
     *   "prefix": "void MyClass::process() {\n  // TODO: implement\n  ",
     *   "context": "...",
     *   "currentFile": "..."
     * }
     */
    @PostMapping("/continue")
    public ContinuationResponse generateContinuation(@RequestBody ContinuationRequest request) {
        log.info("生成代码续写");
        
        return completionService.generateContinuation(
            request.getPrefix(),
            request.getContext(),
            request.getCurrentFile()
        );
    }
    
    /**
     * 查找函数使用示例
     * 
     * GET /api/knowledge/completion/examples/{functionName}
     * 
     * Response:
     * [
     *   { "type": "FUNCTION", "content": "...", ... },
     *   { "type": "TEST_CASE", "content": "...", ... }
     * ]
     */
    @GetMapping("/examples/{functionName}")
    public List<CodeSnippet> findUsageExamples(@PathVariable String functionName) {
        log.info("查找使用示例: {}", functionName);
        
        return completionService.findUsageExamples(functionName);
    }
    
    /**
     * 获取函数参数提示
     * 
     * POST /api/knowledge/completion/parameters
     * 
     * Request:
     * {
     *   "functionName": "napi_create_object",
     *   "currentParams": ["env"]
     * }
     */
    @PostMapping("/parameters")
    public ParameterHintResponse getParameterHints(@RequestBody ParameterRequest request) {
        log.info("获取参数提示: {}", request.getFunctionName());
        
        return completionService.getParameterHints(
            request.getFunctionName(),
            request.getCurrentParams()
        );
    }
    
    // DTO类
    public static class CompletionRequest {
        private String keyword;
        private String currentFile;
        private String context;
        private Integer maxResults;
        private Boolean useCodeQL;  // 是否使用CodeQL增强
        
        // getters and setters
        public String getKeyword() { return keyword; }
        public void setKeyword(String keyword) { this.keyword = keyword; }
        public String getCurrentFile() { return currentFile; }
        public void setCurrentFile(String currentFile) { this.currentFile = currentFile; }
        public String getContext() { return context; }
        public void setContext(String context) { this.context = context; }
        public Integer getMaxResults() { return maxResults; }
        public void setMaxResults(Integer maxResults) { this.maxResults = maxResults; }
        public Boolean getUseCodeQL() { return useCodeQL; }
        public void setUseCodeQL(Boolean useCodeQL) { this.useCodeQL = useCodeQL; }
    }
    
    public static class ContinuationRequest {
        private String prefix;
        private String context;
        private String currentFile;
        
        // getters and setters
        public String getPrefix() { return prefix; }
        public void setPrefix(String prefix) { this.prefix = prefix; }
        public String getContext() { return context; }
        public void setContext(String context) { this.context = context; }
        public String getCurrentFile() { return currentFile; }
        public void setCurrentFile(String currentFile) { this.currentFile = currentFile; }
    }
    
    public static class ParameterRequest {
        private String functionName;
        private List<String> currentParams;
        
        // getters and setters
        public String getFunctionName() { return functionName; }
        public void setFunctionName(String functionName) { this.functionName = functionName; }
        public List<String> getCurrentParams() { return currentParams; }
        public void setCurrentParams(List<String> currentParams) { this.currentParams = currentParams; }
    }
}

